package cn.gdust.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "UploadServlet", value = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    //上传文件的大小
    private final long FILE_SIZE = 1024 * 1024 * 100;

    //上传文件的总大小
    private final long TOTAL_SIZE = 1024 * 1024 * 100;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 判断表单是否为multipart/form-data类型
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // 设置响应内容类型
        response.setContentType("text/html;charset=utf-8");
        if (isMultipart) {
            // 创建DiskFileItemFactory对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建ServletFileUpload对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 设置上传文件的大小限制
            upload.setFileSizeMax(FILE_SIZE);
            // 设置上传文件的总大小限制
            upload.setSizeMax(TOTAL_SIZE);
            // 设置上传文件的头编码
            upload.setHeaderEncoding("UTF-8");
            try {
                // 解析request请求
                List<FileItem> items = upload.parseRequest(request);
                // 遍历items
                for (FileItem item : items) {
                    // 判断item是否为普通表单项
                    if (!item.isFormField()) {
                        // 获取文件名
                        String fileName = item.getName();
                        fileName=mkid()+fileName;
                        // 获取文件路径
                        String filePath = request.getServletContext().getRealPath("/") + "uploads/" + fileName;
                        // 创建文件
                        File file = new File(filePath);
                        // 保存文件
                        item.write(file);
                    }
                }
                // 上传成功
                response.getWriter().println("<h1>文件上传成功</h1>");
            } catch (Exception e) {
                e.printStackTrace();
                // 上传失败
                response.getWriter().println("文件上传失败");
            }
        }
    }
    public static String mkid(){
        return UUID.randomUUID().toString();
    }
}
